﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Entity.FrameEntity;
using CustomAttribute = Entity.FrameEntity.CustomAttribute;

namespace DBService.Handler.Base
{
    internal class TranslationObject
    {
        /// <summary>
        /// 实体对象翻译方法
        /// </summary>
        /// <param name="obj">实体对象</param>
        /// <returns></returns>
        public virtual QueryOption TranslationMode(object obj)
        {
            QueryOption option = new QueryOption();
            var objectType = obj.GetType();
            var cuAttributes = objectType.GetCustomAttributes(true);
            var objectAttribute = (CustomAttribute)cuAttributes[2];//获取模型对象自定义特性
            //var objectAttribute = (Entity.FrameEntity.CustomAttribute)objType.GetCustomAttributes(true)[0];//获取模型对象自定义特性
           
            if (objectAttribute.TableName == null || objectAttribute.TableName.Trim().Equals(""))
            {
                return option;
            }
            else
            {
                option.TableName = objectAttribute.TableName;
            }
            PropertyInfo[] propertys = objectType.GetProperties();
            List<EntityStructure> list = new List<EntityStructure>();
            EntityStructure structsture;
            foreach (PropertyInfo pi in propertys)
            {
                var value = pi.GetValue(obj, null);
                if (value != null && !string.IsNullOrWhiteSpace(value.ToString()))
                {
                    structsture = new EntityStructure();
                    structsture.FileName = pi.Name.Trim();
                    structsture.FileValue = value.ToString().Trim();
                    #region 判断字段属性是否存在
                    if (pi.GetCustomAttributes(true).Length > 0)
                    {
                        var fileAttribute = (FilesAttribute)pi.GetCustomAttributes(true)[0];//获取该字段的自定义特性
                        structsture.Types = fileAttribute.DoType;
                    }
                    else
                    {
                        structsture.Types = QueryType.Equal;
                    }
                    #endregion
                    if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                    {
                        structsture.FileType = Nullable.GetUnderlyingType(pi.PropertyType).Name.ToString();
                    }
                    else
                    {
                        structsture.FileType = pi.PropertyType.Name;
                    }

                    list.Add(structsture);
                }

            }
            option.QueryList = list;

            return option;
        }
    }
}
